/*
 * Copyright (C) 2010 Grummfy
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 */

package org.android.bbox;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.android.bbox.data.Profil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class Box
{
	private Profil profil;

	/**
	 * Current html page
	 */
	private String currentPage;

	/**
	 * Current session id
	 * Filled after auth() call
	 */
	private String session_id;

	/**
	 * The next page to post
	 * 0 : CGI_MODE_EMPTY
	 * 1 : CGI_MODE_0
	 * 2 : CGI_MODE_2
	 */
	private String[] post_page_id;

	public static final int CGI_MODE_EMPTY = 0;
	public static final int CGI_MODE_0 = 1;
	public static final int CGI_MODE_2 = 2;

	public static final int CGI_START_PAGE = 9055;

	public Box(Profil profil)
	{
		this.profil = profil;
		System.out.println(profil);
		this.auth();
	}

	/**
	 * Call page following the js call
	 * @param button_name
	 * @param cgi access mode to the button_name
	 * @return
	 */
	public String mimic_button(String button_name, int cgi)
	{
		String ret = "";

		if (cgi < CGI_MODE_EMPTY || CGI_MODE_2 < cgi)
		{
			cgi = CGI_MODE_EMPTY;
		}

		String encoding = (cgi == CGI_MODE_2)?"multipart/form-data":"application/x-www-form-urlencoded";

		String action = this.post_page_id[ cgi ];

		//POST
		/*
<INPUT type=HIDDEN name="active_page" value="CGI_START_PAGE">
<INPUT type=HIDDEN name="session_id" value="1347182162"> //--> how to extract ...-> première page donne l'info ...
<INPUT type=HIDDEN name="prev_page" value="CGI_START_PAGE">// or 0
<INPUT type=HIDDEN name="page_title" value="Status">//--> don't care
<INPUT type=HIDDEN name="nav_stack_0" value="CGI_START_PAGE">
<INPUT type=HIDDEN name="nav_CGI_START_PAGE_button_value" value="lb_sidebar_advanced_status">//-->button value ou vide
<INPUT type=HIDDEN name="mimic_button_field" value="">//-->button value =>
<INPUT type=HIDDEN name="button_value" value="lb_sidebar_advanced_status">//-->button value => ou vide
<INPUT type=HIDDEN name="transaction_id" value="0">
		 */

		return ret;
	}

	/**
	 * Call a javascript page id
	 * @param pageId
	 * @return
	 */
	public String callJsPage(int pageId)
	{
		return this.mimic_button("navigator: " + pageId + "..", CGI_MODE_EMPTY);
	}

	public String callJsPage(String function, String pageId, int cgi)
	{
		return this.mimic_button(function + ": " + pageId + "..", cgi);
	}

	public String getHtmlString()
	{
		return this.currentPage;
	}

	public String getHtmlString(String url)
	{
		DefaultHttpClient httpclient = new DefaultHttpClient();

		HttpGet get = new HttpGet(url);
		HttpResponse response;
		String txt = "";
		try
		{
			response = httpclient.execute(get);
			HttpEntity entity = response.getEntity();
			BufferedReader buf = new BufferedReader(new InputStreamReader(entity.getContent()));
			String line;

			while((line = buf.readLine()) != null)
			{
				//TODO intérêt? ->> wait answer from profete
				//System.out.println("line" + line);
//				if (line.contains("Digest Algorithm, as defined in RFC 1321"))
//				{
//					System.err.println("-----------------");
//					System.err.println("      ERROR      ");
//					System.err.println("-----------------");
//					System.err.println("Box:getHtmlString()");
//					System.err.println("-----------------");
//					System.err.println(line);
//					System.err.println("-----------------");
//					System.err.println("-----------------");
//					return null;
//				}
				txt += line + buf.readLine();
			}

			if (entity != null)
			{
				entity.consumeContent();
			}
		}
		catch (ClientProtocolException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

		this.currentPage = txt;

		//extract data 
		//get post page value
		int pos = txt.indexOf("action=\"", txt.indexOf("<FORM name=\"form_contents\" method=POST")) + 8;
		this.post_page_id[ this.CGI_MODE_EMPTY ] = txt.substring(pos, txt.indexOf("\"", pos));

		/*
		  switch(cgi) {
		  case 0:
		    f.encoding="application/x-www-form-urlencoded";
		    f.action="/cache/674844112/index.cgi";
		    break;
		  case 2:
		    f.encoding="multipart/form-data";
		    f.action="/cache/942595526/index.cgi";
		    break;
		  }
		  
		  
		  
		  <FORM name="form_contents" method=POST action="/cache/454898802/index.cgi" enctype="application/x-www-form-urlencoded"
		}*/

		return txt;
	}

	/**
	 * Log in as admin user
	 * @see Box:auth(boolean asAdmin)
	 */
	public void auth()
	{
		this.auth(true);
	}

	/**
	 * Log in as user
	 * Extract session inforations
	 * @param asAdmin true : use admin user
	 */
	public void auth(boolean asAdmin)
	{
		//TODO use md5/rsa auth like it's used in the app
		// password  = hex_md5(this.profile.getPassword(); + auth_key)
		// user = this.profile.getLogin();
		// "http://192.168.1.1/index.cgi?user_name=admin&password=BGCVDSL2"
		String auth_url = this.buildUrl("index.cgi?user_name=" +
				this.profil.getLogin() + "&password=" +
				((asAdmin)?this.profil.getPassword():this.profil.getPassword_user()));
		String myDoc = this.getHtmlString(auth_url);

		//get session id
		int pos = myDoc.indexOf("value=\"", myDoc.indexOf("<INPUT type=HIDDEN name=\"session_id\" ", 0)) + 7;
		this.session_id = myDoc.substring(pos, myDoc.indexOf("\"", pos));
	}

	/**
	 * Create url from path
	 * @param path
	 * @return url string
	 */
	public String buildUrl(String path)
	{
		return "http://" + this.profil.getIp() + "/" + path;
	}
}
